package com.youdianstar.app.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.youdianstar.app.databinding.LayoutItemOrderMsBinding
import com.youdianstar.app.entity.NewOrderInfo
import com.youdianstar.app.common.util.DateUtil
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.common.util.MathUtil
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.auko.startActivity
import com.youdianstar.app.ui.OrderDetailActivity
import com.youdianstar.app.R

class OrderOPAdapter(val mContext: Context, val dataList: List<Any>): RecyclerView.Adapter<OrderOPAdapter.ListHolder>() {

    class ListHolder(val binding : LayoutItemOrderMsBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListHolder {
        android.util.Log.d("OrderOPAdapter", "onCreateViewHolder: viewType=$viewType")
        val binding = LayoutItemOrderMsBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        android.util.Log.d("OrderOPAdapter", "ViewHolder created, root view: ${binding.root}")
        android.util.Log.d("OrderOPAdapter", "Root view width: ${binding.root.width}, height: ${binding.root.height}")
        android.util.Log.d("OrderOPAdapter", "Root view visibility: ${binding.root.visibility}")
        return ListHolder(binding)
    }

    override fun getItemCount(): Int {
        android.util.Log.d("OrderOPAdapter", "getItemCount: ${dataList.size}")
        return dataList.size
    }

    override fun onBindViewHolder(holder: ListHolder, position: Int) {
        android.util.Log.d("OrderOPAdapter", "onBindViewHolder: position=$position")
        
        val order = dataList[position]
        when (order) {
            is NewOrderInfo -> {
                // 1. tvName (订单状态) - 后端字段：usingStatus
                val statusText = when (order.usingStatus) {
                    1 -> mContext.getString(R.string.order_status_using)
                    2 -> mContext.getString(R.string.order_status_returned)
                    3 -> mContext.getString(R.string.order_status_purchased)
                    4 -> mContext.getString(R.string.order_status_purchased_lost)
                    5 -> mContext.getString(R.string.order_status_purchased_timeout)
                    else -> mContext.getString(R.string.order_status_unknown)
                }
                holder.binding.tvName.text = statusText
                
                // 2. tvAmount (金额) - 后端字段：payFee (支付金额)
                val symbolStr = DataAppManager.instance.symbolTx()
                holder.binding.tvAmount.text = "$symbolStr ${MathUtil.round(order.payFee)}"
                
                // 3. tvOrderId (订单编号) - 显示uuid，但跳转时传id
                holder.binding.tvOrderId.text = mContext.getString(R.string.order_orderId_label, order.uuid)
                
                // 4. tvDeviceSn (柜机SN) - 后端字段：box1DeviceId (借柜机设备ID)
                holder.binding.tvDeviceSn.text = mContext.getString(R.string.order_cabinet_sn_label, order.box1DeviceId)
                
                // 5. tvTime (租借时间) - 后端字段：createTime (创建时间)
                holder.binding.tvTime.text = mContext.getString(R.string.order_rental_time_label, DateUtil.getOrderTime(order.createTime))
                
                // 6. tvLocation (租借地点) - 后端字段：box1SiteName (借柜机网点名称)
                holder.binding.tvLocation.text = mContext.getString(R.string.order_rental_location_label, order.box1SiteName)
                
                // 7. tvBillingRules (计费规则) - 相关字段组合
                val billingRuleText = mContext.getString(
                    R.string.order_billing_rule_format,
                    order.ruleMinuteFree,
                    MathUtil.round(order.ruleCycleFee),
                    order.ruleMinuteCycle,
                    MathUtil.round(order.ruleDayFee),
                    MathUtil.round(order.ruleSecurityFee)
                )
                holder.binding.tvBillingRules.text = mContext.getString(R.string.order_billing_rule_label, billingRuleText)
                
                // 8. tvActionText (操作按钮) - 根据订单状态动态设置
                when (order.usingStatus) {
                    2 -> {
                        // 已归还 - 显示"去支付"（如果未支付）
                        if (!order.pay) {
                            holder.binding.tvActionText.text = mContext.getString(R.string.order_gotoPay)
                            holder.binding.llBottomAction.setBackgroundColor(0xFFFFF5F5.toInt()) // #fff5f5
                            holder.binding.tvActionText.setTextColor(0xFFFF6B6B.toInt()) // #FF6B6B
                            holder.binding.ivActionArrow.setTextColor(0xFFFF6B6B.toInt()) // #FF6B6B
                        } else {
                            holder.binding.tvActionText.text = mContext.getString(R.string.order_viewOrder)
                            holder.binding.llBottomAction.setBackgroundColor(0xFFFAFAFA.toInt()) // #fafafa
                            holder.binding.tvActionText.setTextColor(0xFF333333.toInt()) // #333333
                            holder.binding.ivActionArrow.setTextColor(0xFF666666.toInt()) // #666666
                        }
                    }
                    else -> {
                        // 其他状态 - 显示"查看订单"
                        holder.binding.tvActionText.text = mContext.getString(R.string.order_viewOrder)
                        holder.binding.llBottomAction.setBackgroundColor(0xFFFAFAFA.toInt()) // #fafafa
                        holder.binding.tvActionText.setTextColor(0xFF333333.toInt()) // #333333
                        holder.binding.ivActionArrow.setTextColor(0xFF666666.toInt()) // #666666
                    }
                }
                
                // 设置点击事件 - 所有订单都可以查看详情
                holder.binding.llBottomAction.setOnClickListener {
                    android.util.Log.d("OrderOPAdapter", "点击查看订单: position=$position, status=${order.usingStatus}, id=${order.id}")
                    // 跳转到订单详情页面，传递订单id
                    mContext.startActivity<OrderDetailActivity>(
                        Extra.IT_ORDERNO to order.id.toString(),
                        Extra.IT_TYPE to 0
                    )
                }
                
                // 同时支持点击整个item查看详情
                holder.binding.root.setOnClickListener {
                    android.util.Log.d("OrderOPAdapter", "点击订单项: position=$position, id=${order.id}")
                    // 跳转到订单详情页面，传递订单id
                    mContext.startActivity<OrderDetailActivity>(
                        Extra.IT_ORDERNO to order.id.toString(),
                        Extra.IT_TYPE to 0
                    )
                }
            }
            else -> {
                // 未知类型，显示默认值
                val symbolStr = DataAppManager.instance.symbolTx()
                holder.binding.tvName.text = mContext.getString(R.string.order_status_unknown)
                holder.binding.tvAmount.text = "$symbolStr 0.00"
                holder.binding.tvOrderId.text = mContext.getString(R.string.order_orderId_label, "--")
                holder.binding.tvDeviceSn.text = mContext.getString(R.string.order_cabinet_sn_label, "--")
                holder.binding.tvTime.text = mContext.getString(R.string.order_rental_time_label, "--")
                holder.binding.tvLocation.text = mContext.getString(R.string.order_rental_location_label, "--")
                holder.binding.tvBillingRules.text = mContext.getString(R.string.order_billing_rule_label, "--")
                holder.binding.tvActionText.text = mContext.getString(R.string.order_viewOrder)
            }
        }
        
        android.util.Log.d("OrderOPAdapter", "绑定完成: position=$position")
    }
}